<template>
  <div class="common-layout" style="margin-top: 50px;">
    <el-container style="margin-left: 100px">
      <el-header>
        <el-menu
          class="el-menu-demo"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
          style="height: 80px; display: flex; align-items: center; justify-content: space-between;"
        >
          <!-- 欢迎信息显示在左上角 -->
          <p style="color: burlywood; margin: 0;">
            欢迎 <span style="color: crimson;">{{ Store.CurrLoginUser.UserName }}</span> 用户登录
          </p>
          <!-- 退出登录按钮显示在右上角 -->
          <el-button link type="primary" size="big" @click="getLogin">退出登录</el-button>
        </el-menu>
      </el-header>
      <el-container style="margin-left: 20px; margin-top: 22px;">
        <el-aside width="200px">
          <el-col :span="12">
            <el-menu
              active-text-color="#ffd04b"
              background-color="#545c64"
              class="el-menu-vertical-demo"
              default-active="2"
              text-color="#fff"
              @open="handleOpen"
              @close="handleClose"
              style="width: 200px;"
              
              router
            >
              <!-- 渲染菜单 -->
              <template v-for="item in menuname" :key="item.menuId" >
                <!-- 如果有子菜单，使用 el-sub-menu -->
                <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.url">
                  <template #title>
                    <span>{{ item.menuName }}</span>
                  </template>
                  <!-- 渲染子菜单 -->
                  <el-menu-item v-for="child in item.children" :key="child.menuId" :index="child.url">
                    {{ child.menuName }}
                  </el-menu-item>
                </el-sub-menu>
                <!-- 如果没有子菜单，直接使用 el-menu-item -->
                <el-menu-item v-else :index="item.url">
                  {{ item.menuName }}
                </el-menu-item>
              </template>
            </el-menu>
          </el-col>
        </el-aside>
        <el-main>
          <RouterView />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter';

let router = useRouter();
let Store = useCounterStore();

// 返回登录页面
const getLogin = () => {
  router.push('/');
};

// 接受菜单数据的变量
const menuname = ref([]);

// 将扁平化菜单数据转换为嵌套结构
const buildMenuTree = (menus: any[]) => {
  const menuMap = new Map(); // 用于存储菜单项
  const menuTree: any = []; // 最终的嵌套菜单结构

  // 将菜单项存入 Map
  menus.forEach((menu) => {
    menu.children = []; // 初始化子菜单
    menuMap.set(menu.menuId, menu);
  });

  // 构建嵌套结构
  menus.forEach((menu) => {
    if (menu.pid == 1) {
      // 一级菜单
      menuTree.push(menu);
      console.log('子集的子集', menuTree);
    } else {
      // 子菜单，添加到父菜单的 children 中
      const parentMenu = menuMap.get(menu.pid);
      console.log('未知', parentMenu);
      if (parentMenu) {
        parentMenu.children.push(menu);
      }
    }
  });

  console.log('树状菜单', menuTree);
  return menuTree;
};

// 获取菜单数据
const getmenu = () => {
  axios({
    url: 'http://localhost:5284/api/Users/GetAll',
    method: 'get',
    params: {
      UserId: Store.CurrLoginUser.userId,
    },
  })
    .then((res) => {
      if (res.data.code == 101) {
        console.log(res);
        // 将扁平化数据转换为嵌套结构
        menuname.value = buildMenuTree(res.data.data);
        console.log('菜单数据', menuname.value);
      }
    })
    .catch((error) => {
      console.error('请求失败', error);
    });
};

onMounted(() => {
  getmenu();
});

const getaaa=()=>{
  router.push("/aaaaaaaa")
}

const handleOpen = (key: string, keyPath: string[]) => {
  console.log('打开菜单:', key, keyPath);
};

const handleClose = (key: string, keyPath: string[]) => {
  console.log('关闭菜单:', key, keyPath);
};
</script>